//导入模块
import { load, isLogin } from "/code/admin/util/LoadView.js"
load("regnews")
const newsListItem = document.querySelector(".newsListItem")
const editNewsForm = document.querySelector("#editNewsForm")
const zhezhao = document.querySelector(".zhezhao")
let photo = ""
let index =""
let content = ""
//渲染新闻列表
async function abcd() {
    let user = JSON.parse(isLogin())
    let res = await fetch(`http://localhost:3000/news/?author=${user.username}`).then(res => res.json())
    document.querySelector(".newsListItem").innerHTML = res.map(function (item) {
        return `<li data-index=${item.id} class="row">
    <span class="col-7 smalltitle" >${item.title}</span>
    <span class="col-2">${item.type}</span>
    <span class="col-3">
    <button type="button" class="btn btn-secondary" id="preview">预览</button>
    <button type="button" class="btn btn-primary" id="edit"}>编辑</button>
    <button type="button" class="btn btn-danger" id="deleteNews">删除</button>
    </span>
    </li>`
    }).join("")
}
abcd()
//将预览，编辑，和删除事件委托给newsListItem
newsListItem.onclick = async function (evt) {
    let user = JSON.parse(isLogin())
    index = evt.target.parentElement.parentElement.dataset.index
    if (evt.target.id == "preview") {//如果点击的是预览
        zhezhao.style.display = "block"
        preview_container.style.display = "block"
        fetch(`http://localhost:3000/news/${index}`).then(res => res.json())
        .then(res => {
            preview_title.innerHTML = res.title
            preview_author.innerHTML = "作者:" + res.author
            preview_content.innerHTML = res.content 
        })
    } else if (evt.target.id == "edit") {//点击的是编辑
        let res = await fetch(`http://localhost:3000/news/${index}`).then(res =>res.json())
        .then(res =>{
            Newstitle.value = res.title
            category.value = res.type
            editor.setHtml(res.content)
            content = res.content
            photo = res.photo
        })
        editNewsForm.style.display = "flex"
        zhezhao.style.display = "block"
    } else if (evt.target.id == "deleteNews") {//点击的是删除
        if (confirm("确定删除吗？")) {
            let res = await fetch(`http://localhost:3000/news/${index}`, {
                method: "DELETE"
            }).then(res => res.json())
        evt.target.parentElement.parentElement.remove()
        alert("删除成功")
        // abcd()
    }
}
}
//添加封面图片时，转换成base64格式
CoverImage.onchange = function(evt){
    let reader = new FileReader()
    reader.readAsDataURL(evt.target.files[0])
    reader.onload = function(e){
        photo = e.target.result
    }
    // console.log(photo)
}
//给修改表单 绑定事件
editNewsForm.onsubmit = async function (evt) {
    evt.preventDefault()
    let user = JSON.parse(isLogin())
    let res = await fetch(`http://localhost:3000/news/${index}`, {
        method: "PATCH",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            title: Newstitle.value,
            type:category.value,
            content,
            photo
        })
    }).then(res => res.json())
    editNewsForm.style.display = "none"
    zhezhao.style.display = "none"
    // alert("修改成功")
    abcd()
}
//给取消修改 绑定事件
edit_cancel.onclick = function () {
    editNewsForm.style.display = "none"
    zhezhao.style.display = "none"
}
//给取消预览绑定事件
preview_cancel.onclick = function () {
    preview_container.style.display = "none"
    zhezhao.style.display = "none"
}
//富文本编辑器
const { createEditor, createToolbar } = window.wangEditor
const editorConfig = {
    placeholder: '',
    onChange(editor) {
        const html = editor.getHtml()
        //   console.log(html)
        // 也可以同步到 <textarea>
        content = html
        // console.log(content)
    }
}

const editor = createEditor({
    selector: '#editor-container',
    html: '<p><br></p>',
    config: editorConfig,
    mode: 'default', // or 'simple'
})

const toolbarConfig = {}
//富文本编辑器的工具栏
const toolbar = createToolbar({
    editor,
    selector: '#toolbar-container',
    config: toolbarConfig,
    mode: 'default', // or 'simple'
})
